'use strict';
const log = require('../logger');
const musixmatch = require('./musixmatchLyrics');
const deezerApi = require('deezer-request2');
/**
 * Get lyrics of a track by id.
 *
 * @param {Number} id
 */
const getTrackLyrics = async (trackInfos) => {
  if (trackInfos.LYRICS) return null;

  if (trackInfos.LYRICS_ID > 0) {
    try {
      const { data } = await deezerApi.getLyrics(trackInfos.SNG_ID);
      if (data && data.error.length == 0 && data.results && data.results.LYRICS_ID) {
        log.debug(`Lyrics fetched from deezer: ${trackInfos.SNG_TITLE}, ${trackInfos.SNG_ID}`);
        return data.results;
      }
    } catch (err) {
      log.debug(`Lyrics error deezer: ${trackInfos.SNG_TITLE}, ${trackInfos.SNG_ID}, ${err}`);
      return await getTrackLyricsWeb(trackInfos);
    }
  }

  return await getTrackLyricsWeb(trackInfos);
};

const getTrackLyricsWeb = async (trackInfos) => {
  try {
    const url = await musixmatch.getURL(`${trackInfos.ART_NAME} - ${trackInfos.SNG_TITLE_VERSION}`);
    const lyrics = await musixmatch.getLyrics(url);
    log.debug(`Lyrics fetched from musixmatch: ${trackInfos.SNG_TITLE}, ${trackInfos.SNG_ID}`);
    return { LYRICS_TEXT: lyrics };
  } catch (err) {
    log.debug(`Lyrics error musixmatch: ${trackInfos.SNG_TITLE}, ${trackInfos.SNG_ID}, ${err}`);
    return null;
  }
};

module.exports = getTrackLyrics;
